// 引用各模块路由
const userRouter = require('./src/router/userRouter')
const blogRouter = require('./src/router/blogRouter')
const querystring = require('querystring')
const getPostData = require('./src/utils/getPostData')

const SESSION_DATA = {}
const serveHandle = async (req, res) => {
  // 设置返回格式为JSON
  res.setHeader('Content-Type', 'application/json')
  // 解析url 和 解析get参数
  req.path = req.url.split('?')[0]
  req.query = querystring.parse(req.url.split('?')[1])

  // 解析cookie 并存储到 req.cookie中
  if (req.headers.cookie) {
    let cookieObj = {}
    let cookieArr = req.headers.cookie.split(';')
    cookieArr.map((o) => {
      let key = o.split('=')[0].trim() //去掉空格避免解析错误
      let value = o.split('=')[1].trim() //去掉空格避免解析错误
      cookieObj[key] = value
    })
    req.cookie = cookieObj
    console.log(req.cookie, '--- req cookie ---')
  }
  // -------  解析session start --------
  let needSetCookie = false
  let userId = req.cookie.userId
  if (userId) {
    if (!SESSION_DATA[userId]) {
      SESSION_DATA[userId] = {}
    }
  } else {
    needSetCookie = true
    userId = `${Date.now()}_${parseInt(Math.random() * 10)}`
    SESSION_DATA[userId] = {}
  }
  req.session = SESSION_DATA
  // ------- 解析session  end ----------

  console.log(req.session, '--- req session  40 ---')

  // 解析post参数
  req.body = await getPostData(req)

  let isExitBlog = await blogRouter(req, res)
  console.log(isExitBlog, '--- isExitBlog ---')

  if (isExitBlog) {
    if (needSetCookie) {
      res.setHeader('Set-Cookie', `userId=${userId}; path=/; httpOnly`)
    }
    res.end(JSON.stringify(isExitBlog))
    return
  }

  let isExitUser = await userRouter(req, res)
  if (isExitUser) {
    if (needSetCookie) {
      res.setHeader('Set-Cookie', `userId=${userId}; path=/; httpOnly`)
    }
    res.end(JSON.stringify(isExitUser))
    return
  }
  res.end(JSON.stringify({ message: '404 Not Found' }))
}

module.exports = serveHandle
